package netclient;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
	final static String 	HOST = "localhost";
	final static int 		PORT = 8576;

	static Socket sock = null;
	static PrintWriter netOut;
	static Scanner netIn;

	static MessageHandler msgHand;
	
	private static void setup() {
		while (sock == null) {
			try {
				System.out.println("Attempting to connect to: " + HOST + ":" + PORT);
				sock = new Socket(HOST, PORT);
				netOut = new PrintWriter(sock.getOutputStream());
				netIn = new Scanner(sock.getInputStream());
			} catch (Exception e) {
				try {Thread.sleep(5000);} catch(Exception e2) {};
			}
		}

//		System.out.println("preparing to construct msgHand");
//		msgHand = new MessageHandler(sock, netIn, resultStream);
//		msgHand.start();
	}
	
	public static String sendMessage( String s) {
		if (sock == null) setup();
		
		//set up message handler
		ReturnObject response = new ReturnObject(); 
		msgHand = new MessageHandler(sock, netIn, response);
		msgHand.start();
		
		boolean flag = false;
		while (!flag) {
			try {
				netOut.println(s);
				netOut.flush();
				flag = true;
			} catch (Exception e) {
				flag = false;
			}	
		}
		
		boolean f = true;
		while(f){
			
				if (response.getData().equals("")){
				}
				else {
					break;
				}
			}
		//
		 System.out.println("Client has: " + response.getData());
		
		return response.getData();
	}
		
	
	
	public void finalize() {
		System.err.println("finalizing");
		try {
			sendMessage("bye");
			netIn.close();
			sock.close();
			netOut.close();
		} catch(Exception e) {}
		
		sock = null;
	}
}
